package it.unibo.deis.lia.mmhc.spm;

import it.unibo.deis.lia.mmhc.nip.NetworkInterfaceProvider;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.Socket;

public class ServicePathServerThread extends Thread{
	
	private Socket input=null;
	private SocketVector socketVector=null;

	public ServicePathServerThread(Socket input) {
		super();
		this.input = input;
		socketVector=SocketVector.getInstance();
	}
	public void run(){
		try{
			while(input.isConnected()){
			ObjectInputStream ois = new ObjectInputStream(input
		
				.getInputStream());

		
			Object obj = ois.readObject();
			
		
		ServicePacket packet = (ServicePacket) obj;
		
		if (packet.getFornitore().equalsIgnoreCase(
				NetworkInterfaceProvider.getMyUniversalName())
				&& packet.isGo()) {
		
					Socket out = socketVector.getSoket("127.0.0.1", packet.getPort());
					setSok(packet, out);
				
				
			ObjectOutputStream oos = new ObjectOutputStream(out
					.getOutputStream());
			oos.flush();
			oos.writeObject(packet.getObj());
			oos.flush();
			// out.close();
		} else if (packet.getRichiedente().equalsIgnoreCase(
				NetworkInterfaceProvider.getMyUniversalName())
				&& !packet.isGo()) {
			
			try {
				Socket sock = socketVector.getSoket("127.0.0.1", packet.getPort());
				ObjectOutputStream oos = new ObjectOutputStream(sock
						.getOutputStream());
				oos.flush();
				oos.writeObject(packet.getObj());
				oos.flush();
				sock.close();
			} catch (Exception e) {
				System.err.println("\t errore in posizione 2" + e);
			}
			// out.close();
		} else {
			String nextHop = packet.nextHop();
			System.err.println("Ricevuto pacchetto diretto a "
					+ nextHop);
			try {
				// Socket out = getsocket(socketOut, nextHop);
				
						Socket out = socketVector.getSoket(nextHop, 2500);
						
					
					
				ObjectOutputStream oos = new ObjectOutputStream(out
						.getOutputStream());
				oos.flush();
				oos.writeObject(packet);
				oos.flush();
			} catch (Exception e) {
				System.err.println("\t errore in posizione 3" + e);
			}

			// out.close();
		}}
		}catch (Exception e) {
			// TODO: handle exception
		}

		// input.close();
	}
	private void setSok(ServicePacket server, Socket out) {
		for (int i = 0; i < ServicePathServer.serviceServer.size(); i++) {

			if (ServicePathServer.serviceServer.elementAt(i).getPort() == server.getPort()
					&& ServicePathServer.serviceServer.elementAt(i).getFornitore()
							.equalsIgnoreCase(server.getFornitore())
					&& ServicePathServer.serviceServer.elementAt(i).getRichiedente()
							.equalsIgnoreCase(server.getRichiedente())) {
				ServicePathServer.serviceServer.elementAt(i).setSoket(out);
			}
		}

	}

}
